package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.ChatMessage;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.ChatMessageMapper;
import cn.wolfcode.trip.base.mapper.UserMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IChatMessageService;
import cn.wolfcode.trip.base.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ModelAttribute;

import java.util.List;
import java.util.Set;

@Service
public class ChatMessageServiceImpl implements IChatMessageService {

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void save(ChatMessage chatMessage) {
        chatMessageMapper.insert(chatMessage);
    }

    @Override
    public List<ChatMessage> selectAllForList(QueryObject qo) {
        return chatMessageMapper.selectForList(qo);
    }

    @Override
    public void updateStatus() {
        chatMessageMapper.updateStatus();
    }

    @Override
    public List<User> selectChatSet(Long userId) {
        Set<Long> set1 = chatMessageMapper.queryChatSetBySenderId(userId);
        Set<Long> set2 = chatMessageMapper.queryChatSetByreceiverId(userId);
        set1.addAll(set2);
        System.out.println(set1);
        List<User> chatList = userMapper.selectForChatSet(set1);
        //获得当前登录用户
        Long currentUserId = UserContext.getCurrentUser().getId();
        //查询未读信息数
        for (User user : chatList) {
            user.setUnreadNum(chatMessageMapper.countForUnreadByTwoPerson(currentUserId,user.getId()));
            user.setChatMessage(chatMessageMapper.selectByLastDate(currentUserId,user.getId()));
        }


        return chatList;
    }

    @Override
    public Integer countForUnreadByUserId(Long userId) {
        return chatMessageMapper.countForUnreadByUserId(false,userId);
    }
}
